﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Data.SqlClient;
using System.Data;
using Waker.Common;
using System.Windows.Forms;

namespace Waker.DAL
{
    public class SqlNotifyHelper : DAL_Base, IDisposable
    {
        public string name;
        //private string _strSql;
        //private Form _Form;
        Delegates.DelegateVoid _Del;
        bool IsDisposed = true;
        public void NotifyStart(Delegates.DelegateVoid del)
        {
            _Del = del;
            //_Form = form;
            SqlDependency.Start(base.Db.ConnectionString);//传入连接字符串,启动基于数据库的监听
            Notify();
        }
        private void Notify()
        {
            ThreadPool.QueueUserWorkItem((obj) =>
            {
                using (SqlConnection connection = new SqlConnection(base.Db.ConnectionString))
                {
                    //依赖是基于某一张表的,而且查询语句只能是简单查询语句,不能带top或*,同时必须指定所有者,即类似[dbo].[]
                    using (SqlCommand command = new SqlCommand("select id,userid,[message] from [dbo].[messages] where CreateDate>@CreateDate", connection))
                    {
                        command.CommandType = CommandType.Text;
                        command.Parameters.Add("CreateDate", SqlDbType.DateTime).Value = Session.LastEventTime;
                        connection.Open();
                        SqlDependency dependency = new SqlDependency(command);
                        dependency.OnChange += new OnChangeEventHandler((sender, e) =>
                        {
                            Notify();
                        });
                        SqlDataAdapter sda = new SqlDataAdapter(command);
                        DataTable dt = new DataTable();
                        sda.Fill(dt);
                        //线程安全，使用Dispatch线程更新界面
                        DispatchUpdateUI(dt);
                    }
                }
            });
        }

        private void DispatchUpdateUI(DataTable dt)
        {
            try
            {
                //if (_Form != null && _Del != null)
                //{
                //    _Form.Invoke(_Del);
                //}
                if (_Del != null)
                    _Del();
                //foreach (DataRow dr in dt.Rows)
                //{

                //}
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        protected void Dispose(bool Diposing)
        {
            if (!IsDisposed)
            {
                SqlDependency.Stop(base.Db.ConnectionString);
            }
        }
        ~SqlNotifyHelper()
        {
            Dispose(false);

        }
    }
}
